<html>
<head>
<?php 
$friends_in_row=$_REQUEST['size'];
if ($friends_in_row=='')
	$friends_in_row = 5;
if (stripos($_SERVER['HTTP_USER_AGENT'],'iphone') > 0 || $_REQUEST['debugiphone'] == '1') {
	// we are iphone
	//$dim = 'width="18%"'; 
	$dim = 'width="100%"'; 
	//$dim = 'width=18';
	$friend_pic_size=18;
	//$div_size=$friend_pic_size*$friends_in_row + '%';
	
	$div_size='95%';
	}
	else
	{
		$dim = 'width="80" height="80"';
		$friend_pic_size=80+3; // add cell border
		$div_size=$friend_pic_size*$friends_in_row + 20;
	}
?>
<style type="text/css">
#profile_pics
{
margin:auto;
width:<?php echo($div_size)?>;
padding:10px;
border:5px solid gray;
}
</style>
<title>Facebook Friends Minesweeper</title>
 <meta name = "viewport" content = "width=device-width">
</head>
<body>
Facebook Friends Minesweeper (version 0.1.$Rev: 23 $)<br/>
<?php require_once("fbconnect.php"); ?>
<div id="connectdiv">
please connect:
<fb:login-button v="2" size="medium" onlogin="window.location.reload(true);">Connect</fb:login-button>
</div>
<br>
Can You Recognize Your friends?<br>
Instructions: <br> <div id=scorename>Score:</div><div id=score>0</div>
After all your friends are loaded, click the ones who are your friends, but don't click the one who isn't your friend.<br>
<br>
<div id="profile_pics"></div>
<div id="debug"></div>
<script type="text/javascript">

myindexOf = function( arr,v) {
if (arr.length == 0)
	return -1;
 for( var i =  0, l =  arr.length; i < l; i++ ) {
  if(  arr[i]==v ) { return i; }
 }
 return -1;
};


var ids=new Array();
var idsClicked=new Array();
var pics=new Array();
var names=new Array();
var markupAfterClicking=new Array();
var wrongIndex;
var wrongmarkup;
var friends;
var rowlength = <?php echo($friends_in_row)?>;
var count = rowlength*rowlength;
var clicked = count;
var score=0;
var startTime;
var loadTime= new Date();
var lastTime=0;
var gameOver = false;
var mySession;
var myUID;

var foepics=new Array();

var debug_flag = <? echo $_REQUEST["debug"]=="1" ? "true" : "false";?>;
function debugy(text)
{
	if (!debug_flag)
		return;
	
	var debug_div= document.getElementById("debug");
	var timenow = new Date();
	//debug_div.innerHTML +=  timenow +  " (" +(timenow-loadTime)+"): " +text + "<br>";
	debug_div.innerHTML +=  " (" +(timenow-loadTime)+"): " +text + "<br>";
}

function updateScoreDiv()
{
	var score_div= document.getElementById("score");
	score_div.innerHTML = score;
}

function buildMarkup() {
	
  var widget_div = document.getElementById("profile_pics");
  widget_div.innerHTML = "Loading: Getting pics and building table...";
  FB.Facebook.apiClient.fql_query("SELECT pic_square, first_name , last_name,uid FROM user WHERE uid in (" + 
	ids.join(",") + ")",
		function(rows) {
			for (var i=0; i<rows.length; i++){
				pics[i] = rows[i].pic_square;
				names[i] = "<a href='http://www.facebook.com/profile.php?id="+ rows[i].uid +"' target='new'>" + rows[i].first_name + " " +rows[i].last_name + "</a>";
			}
			var markup="<table border='2'>";
			for (var i=0; i<ids.length; i++) {
				if (i % rowlength == 0){
					if (i > 0) 
						markup += "</tr>";
					markup += "<tr align='center' valign='top'>";
				}
									
				markup += '<td style="position:relative;" border=3 ';
				
				$dim='';
				
				var onclickvar;
				if (i == wrongIndex) 
					onclickvar = ' onClick="clickedWrongFriend(this);"';
				else
					onclickvar = ' onClick="clickedRightFriend(this,' + i +');"';
					
				markup += onclickvar;
				
				idsClicked[i] = false;
			//debugy('adding: <img src="' + pics[i] + ' " <?=$dim?> title="Click me" ></img>');
				markup += '<img src="' + pics[i] + ' " <?=$dim?> title="Click me"></img></td>';
				markupAfterClicking[i] = 
					'<div class="pic_container" style="position:relative" <?=$dim?>>'+
					'<img style="z-index:-1; opacity:0.4;filter:alpha(opacity=40)"'+
					' <?=$dim?> title="Click me" src="' + pics[i] + '"></img>' +
					'<h3 style="position:absolute; top:0px; text-align:center; color:green; margin:auto;">' + names[i] + '</h3>';
					'</div>';
	//		markup += '<fb:profile-pic size="square" uid="' + ids[i] + '" facebook-logo="false" linked="false" 	<?=$dim?> ></fb:profile-pic></a>';
				
			}
			markup+="</tr></table>";

			widget_div.innerHTML = "<CENTER>" + markup + "</CENTER>";
			//FB.XFBML.Host.parseDomElement(widget_div);
			startTime=new Date();
		})
}

function callPublish(msg, attachment, action_link) {
  FB.ensureInit(function () {
    FB.Connect.streamPublish('', attachment, action_link);
  });
}


function clickedWrongFriend(inObj)
{
	if (gameOver)
		return;
	
	inObj.innerHTML='WRONG!<br>' + wrongmarkup ; 
	alert('Game Over! You Lose. Reload page to play again.');
	gameOver=true;
}

function clickedRightFriend(inObj,inID)
{
	if (gameOver)
		return;
		
	if (idsClicked[inID]) 
		return;
		
	idsClicked[inID]=true;
	inObj.innerHTML=markupAfterClicking[inID]; 
		
	score++;
	updateScoreDiv();
	
	if (--clicked == 1)
	{
	
		var endTime = new Date();
		var timeDiff = endTime - startTime;
		//alert ("time : " + timeDiff);
		//alert("Congratulations! You win! Reload page to play again.");
		gameOver=true;
		callPublish('',{'name':'Do you know who are your friends?','href':'http://deceipt.corbomitegames.com/index5.php','description':'I just won a game of friendsweeper and successfully proved i know who my friends are','media':[{'type':'image','src':'imgurl','href':'http://deceipt.corbomitegames.com/index5.php'}]},null);

	}
}

function init() {
// detect if the user is currently logged in,
 mySession = FB.Facebook.apiClient.get_session();
 debugy("mySession = " + mySession);
 var connectdiv = document.getElementById("connectdiv");
 if (!mySession) {
	debugy("no session, adding connect button");
	connectdiv.innerHTML = 'please connect: <fb:login-button v="2" size="medium" onlogin="window.location.reload(true);">Connect</fb:login-button>';
	
 }  else {
  	connectdiv.innerHTML = '';
 }
 debugy("wating for session...");
 //div.innerHTML = 'Waiting until session is ready';
	//FB.Facebook.get_sessionState().waitUntilReady(start);
	
	FB.Facebook.apiClient.get_sessionWaitable().waitUntilReady(start);
	debugy("called start..");
}

function start(inSession) {
debugy("in start()");
//mySession = FB.Facebook.apiClient.get_session();
mySession = inSession;
debugy("mySession = "+mySession);
debugy("mySession.expires = "+mySession.expires);
myUID=mySession.uid;
debugy("myUID = "+myUID);
var connectdiv = document.getElementById("connectdiv");
connectdiv.innerHTML = '';
  var widget_div = document.getElementById("profile_pics");
  widget_div.innerHTML = "Loading (Getting Friends)...";
  
  FB.Facebook.apiClient.fql_query(
		"SELECT uid, pic_square FROM user where uid in (SELECT uid2 from friend WHERE uid1 =" + 
		myUID+ ")",  function(result) {
    //sleep(1000);
	var widget_div = document.getElementById("profile_pics");
	widget_div.innerHTML = "Loading (Got Friends)...";
    friends = result;
    var num_friends_needed = friends ? Math.min(count-1, friends.length - 1) : 0;
    var random_friends_added = 0;
		var safety = 0;
		while (safety < 1000 && random_friends_added < num_friends_needed) 
		{
			safety++;
			widget_div.innerHTML = "Loading (Getting Friends (" +random_friends_added + "/ "+ num_friends_needed + " ) safety ("+safety+ ") )...";
			debugy("Loading (Getting Friends (" +random_friends_added + "/ "+ num_friends_needed + " ) safety ("+safety+ ") )...");
			var myrand = Math.floor(Math.random() * friends.length);
			//debugy("myrand " + myrand  + " friends.length " + friends.length);
			var newid = friends[myrand].uid;
			//debugy("newid " + newid );
			var pic_square = friends[myrand].pic_square;
			//debugy("pic_square " + pic_square + "<img src='"+ pic_square +"'>");
			debugy("ids" + ids);
			//debugy("ids.len" + ids.length);
			//debugy("...");
			//debugy("ids0." + myindexOf(ids,newid));
			//debugy("...");

			// no duplicates and no faceless allowed
			if (myindexOf(ids,newid) < 0 && pic_square && pic_square != "")
			{
				//debugy("pushing.");
				ids.push(newid);
				random_friends_added++;
				//debugy("pushed.");
			}
			
			//debugy("lalala");
		}
		widget_div.innerHTML = "Loading (Getting Groups Fast)...";
		//getGroup();
		getGroupFast();
		//getEvents();
		//getRandomNonFriend(friends[Math.floor(Math.random() * friends.length)]);
  });
}

function getEvents() {

 var widget_div = document.getElementById("profile_pics");
  widget_div.innerHTML = "Loading (Getting events)";

FB.Facebook.apiClient.events_get(null,  null,  0,  0,  "",  function(result) {
  widget_div.innerHTML = "Loading (got events).";
  var randid = result[Math.floor(Math.random() * result.length)].eid;
 alert ("event " + randid);
 
 FB.Facebook.apiClient.events_getMembers(randid,   function(result) {
  widget_div.innerHTML = "Loading (got event members).";
  alert ("event len " + result.length);
 });
 
});

}

function getGroupFast() {
	 var widget_div = document.getElementById("profile_pics");
  
widget_div.innerHTML = "Loading (Getting Groups FQL, it can take a minute or two)...";
  //var mySession = FB.Facebook.apiClient.get_session();
  debugy("Loading (Getting Groups FQL Session" + mySession+")...");
  if (!mySession) {
	widget_div.innerHTML = "Loading (Getting Groups FQL Session = null!)...";	
  }
  
  
  FB.Facebook.apiClient.fql_query("SELECT gid FROM group_member WHERE uid = " + myUID,
		 function(rows) {
		   debugy("total groups  " + rows.length );	
		   var new_gid_idx = Math.floor(Math.random() * (rows.length));
		   debugy("new_gid_idx  " + new_gid_idx);
		   var new_gid = rows[new_gid_idx ].gid;
		   debugy(" new_gid " + new_gid + " url - <a href='http://www.facebook.com/group.php?gid=" + new_gid + "'>link</a>");
		   widget_div.innerHTML = "Loading (Getting foes from groups, can also take a minute or two)...";
		   FB.Facebook.apiClient.fql_query(
				"SELECT uid, pic_square FROM user where uid in " +
				"(SELECT uid FROM group_member WHERE gid = " + new_gid + " LIMIT 30)",
          function(members) {
					widget_div.innerHTML = "Loading (Removing faceless foes)...";
					var membersIds = new Array();
		      var dummy = new Array();
			  debugy("members.length = " + members.length);
			  if (!members) {
					window.location.reload();
					return;
				}
		      for (var i=0; i<members.length; i++) {
						if (members[i].pic_square && members[i].pic_square != "") {
							dummy.push(myUID);
							membersIds.push(members[i].uid);
							foepics[members[i].uid]= members[i].pic_square; // for debug
						}
					}
		      membersIds.sort(function() {return (Math.random()<0.5);});

		      widget_div.innerHTML = "Loading (Checking if the foes are actually friends)...";
		      FB.Facebook.apiClient.friends_areFriends(dummy, membersIds, function(result) {
				if (!result) {
					window.location.reload();
					return;
				}
		        wrongIndex = Math.floor(Math.random() * (ids.length+1));
				debugy("len = " + result.length + " wrongInderx = " + wrongIndex + " myUID= "+myUID);
				var id=0;
		        while ((id<result.length)&&((result[id].are_friends || result[id].uid2 == myUID ))) {
				debugy("id=" + id + " " + result[id].uid2);
		          id++;					
				  }
		        if (id >= result.length)  {
					debugy("id=" + id + " id >= result.length");
					window.location.reload();
					//getGroupFast(); // can't find a freind, call this function again look for another group. -- for some reason it doesn't work.
		        }else {
					// insert the foe into the list!
					debugy("Foe is :<a href='http://www.facebook.com/profile.php?id="  + result[id].uid2 +  "'> index " + wrongIndex + " ("+ (Math.floor(wrongIndex/rowlength)+1) + ","+((wrongIndex%rowlength)+1) + ") id:"  + result[id].uid2 + " pic <img src='" + foepics[result[id].uid2]  +"'></a>");
					wrongmarkup = "<a href='http://www.facebook.com/profile.php?id=" + result[id].uid2  + "' target='new'>Profile</a>";
					debugy("my id=" + myUID);
		          ids.splice(wrongIndex, 0, result[id].uid2);
		          buildMarkup();
		        }
		      });
		    });				
		 });
}

function getGroup() {
	 var widget_div = document.getElementById("profile_pics");							 
								 
  widget_div.innerHTML = "Loading (Getting Groups, it can take a minute or two)...";
  FB.Facebook.apiClient.groups_get(null, null, function(result) {
  	widget_div.innerHTML = "Loading (Parsing groups, Getting friends from groups, can also take a minute or two)...";
    var g = result[Math.floor(Math.random() * result.length)];
    FB.Facebook.apiClient.groups_getMembers(g.gid, function(result) {
      var members = result.members;
      var dummy = new Array();
      //var uid = FB.Facebook.apiClient.get_session().uid;
      for (var i=0; i<result.members.length; i++) dummy.push(myUID);
      members.sort(function() {return (Math.random()<0.5);});

      widget_div.innerHTML = "Loading (Parsing groups 2)...";
      FB.Facebook.apiClient.friends_areFriends(dummy, result.members, function(result) {
      	widget_div.innerHTML = "Loading (Parsing groups 3)...";
        wrongIndex = Math.floor(Math.random() * (ids.length+1));
	var id=0;
        while ((id<result.length)&&(result[id].are_friends))
          id++;
        if (id >= result.length) getGroup;
        else {
          ids.splice(wrongIndex, 0, result[id].uid2);
          buildMarkup();
        }
      });
    });
  });
}


FB.ensureInit(init);


</script>





</body>
</html>
